
<template>
  <div class="app" v-loading="formLoading">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="80px"
      label-position="top"
      style="width: 95%"
    >
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>必填信息</span>
        </div>
        <el-row>
          <el-col :span="6" :offset="1">
            <el-form-item label="用户名(登录账号):" prop="userName" class="">
              <el-input
                v-model="formData.userName"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="密码(登录密码):" prop="passWord">
              <div style="display: flex">
                <el-input
                  v-model="formData.passWord"
                  placeholder="请输入密码"
                  v-if="showPassWord"
                ></el-input>
                <el-button
                  type="warning"
                  @click="resetPassWord(true)"
                  v-show="!showPassWord"
                  >重置密码</el-button
                >
                <el-button
                  type="primary"
                  @click="resetPassWord(false)"
                  v-show="showPassWord"
                  >取消重置</el-button
                >
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="昵称:" class="" prop="nickName">
              <el-input
                v-model="formData.nickName"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" :offset="1">
            <el-form-item label="真实姓名:" class="" prop="realName">
              <el-input
                v-model="formData.realName"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>选填信息</span>
        </div>
        <el-row>
          <el-col :span="6" :offset="1">
            <el-form-item label="电话:" class="" prop="phone">
              <el-input
                v-model="formData.phone"
                placeholder="请输入电话"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="邮箱:" class="" prop="email">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="1">
            <el-form-item label="生日:" class="" prop="birthday">
              <el-date-picker
                v-model="formData.birthday"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" :offset="1">
            <el-form-item label="头像:" class="">
              <OneImage
                ref="oneImage"
                :key="formData.avatar"
                :imageUrl="formData.avatar ? imageUrl(formData.avatar) : ''"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6" :offset="1">
            <el-form-item label="性别:" prop="sex">
              <el-radio v-model="formData.sex" label="男">男</el-radio>
              <el-radio v-model="formData.sex" label="女">女</el-radio>
              <el-radio v-model="formData.sex" label="未知">未知</el-radio>
            </el-form-item>
          </el-col>

          <el-col :span="6" :offset="1">
            <el-form-item label="详细地址:" class="" prop="belongs">
              <el-input
                v-model="formData.belongs"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-card class="footer">
      <el-button @click="reset()">重置</el-button>
      <el-button type="primary" @click="submit('form')">确认</el-button>
    </el-card>
    <div style="height: 120px"></div>
  </div>
</template>

<script>
const checkZc = (rule, value, callback) => {
  if (new RegExp("[^\\w]").test(value)) {
    return callback(new Error("只能由字母数字下划线组成"));
  } else {
    callback();
  }
};
const checkPhone = (rule, value, callback) => {
  if (typeof value != "string" || value === "") {
    return callback();
  }
  if (!/^1[3456789]\d{9}$/.test(value)) {
    return callback(new Error("电话号码格式错误"));
  } else {
    callback();
  }
};

const checkEmail = (rule, value, callback) => {
  if (typeof value != "string" || value === "") {
    return callback();
  }
  if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(value)) {
    return callback(new Error("邮箱格式错误"));
  } else {
    callback();
  }
};

import OneImage from "@/components/uploadImages/OneImage";
import { mapActions } from "vuex";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    OneImage,
  },
  data() {
    //这里存放数据
    return {
      activeNames: ["1", "2"],
      formData: {
        userName: "",
        // passWord:"",
        nickName: "",
        realName: "",
        phone: "",
        email: "",
        birthday: "",
        sex: "未知",
        belongs: "",
        avatar: "",
      },
      oldFormData: {},
      rules: {
        userName: [
          { required: true, message: "用户名不为空", trigger: "blur" },
          { max: 20, message: "长度不超过20个字符", trigger: "blur" },
          { min: 5, message: "长度至少5个字符", trigger: "blur" },
          { validator: checkZc, trigger: "blur" },
          { validator: this.checkUserNameFunc, trigger: "blur" },
        ],
        passWord: [
          { required: true, message: "密码不为空", trigger: "blur" },
          { max: 20, message: "长度不超过20个字符", trigger: "blur" },
          { min: 5, message: "长度至少5个字符", trigger: "blur" },
          { validator: checkZc, trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "昵称不为空", trigger: "blur" },
          { max: 20, message: "不超过20个字符" },
        ],
        realName: [
          { required: true, message: "真实姓名不为空", trigger: "blur" },
          { max: 20, message: "不超过20个字符" },
        ],
        phone: [{ validator: checkPhone, trigger: "blur" }],
        email: [{ validator: checkEmail, trigger: "blur" }],
        // linkman_id: [
        //   { required: true, message: "联系人不为空", trigger: "blur" },
        // ],
      },
      formLoading: false,
      admins_id: "",
      showPassWord: false,
      footerShow: true,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    ...mapActions("admins", ["mineMsg", "mineMsgEdit", "checkUserName"]),
    ...mapActions("upload", ["uploadOneFile"]),
    async mineMsgLoad() {
      this.formLoading = true;
      //  if (this.formData.hasOwnProperty("passWord")) {
      //   delete this.formData.passWord;
      // }
      if (this.rules.hasOwnProperty("passWord")) {
        delete this.rules.passWord;
      }
      let res = await this.mineMsg();
      if (res.code == 200) {
        let data = res.data;
        Object.keys(this.formData).map((item) => {
          this.formData[item] = data[item];
          this.oldFormData[item] = data[item];
        });
      }
      this.resetPassWord(false)

      this.formLoading = false;
    },
    reset() {
      this.formData = JSON.parse(JSON.stringify(this.oldFormData));
    },
    resetPassWord(bool) {
      if (bool) {
        // this.rules.passWord = ;
        // this.formData.passWord = "";
        this.$set(this.rules, "passWord", [
          { required: true, message: "密码不为空", trigger: "blur" },
          { max: 20, message: "长度不超过20个字符", trigger: "blur" },
          { validator: checkZc, trigger: "blur" },
        ]);
        this.$set(this.formData, "passWord", "");
      } else {
        // if (this.rules.hasOwnProperty("passWord")) {
        this.$refs.form.clearValidate('passWord')

        delete this.rules.passWord;
        // }
        delete this.formData.passWord;
      }
      this.showPassWord = bool;
    },
    async checkUserNameFunc(rule, value, callback) {
      let res = await this.checkUserName({ userName: value });
      if (res.code == 200) {
        if (res.data.result == "error") {
          return callback(new Error("该账号已存在"));
        } else if (res.data.result == "success") {
          callback();
        }
      }
    },
    submit(formName) {
      // console.log(11)
      this.$confirm("确定要编辑吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              this.formLoading = true;

              let fileData = this.$refs.oneImage.getFile();
              if (fileData.has("file")) {
                if (!fileData.get("file")) {
                  this.formData["avatar"] = "";
                } else {
                  let fileRes = await this.uploadOneFile(fileData);
                  if (fileRes.code == 200) {
                    this.formData["avatar"] = fileRes.data.url;
                  } else {
                    return;
                  }
                }
              }
              let res = await this.mineMsgEdit({ formData: this.formData });
              if (res.code == 200) {
                this.$message({
                  message: "编辑成功",
                  type: "success",
                });
              }
              this.formLoading = false;
              this.mineMsgLoad()
            } else {
              // console.log('error submit!!');
              this.$message.error("信息填写错误");
              return false;
            }
          });
        })
        .catch(() => {});
    },
  },
  //生命周期 - 创建完成(可以访问当前this实例)
  created() {
    this.mineMsgLoad();
    //   console.log()

    //   this.footerShow = false
    // setTimeout(()=>{
    //    this.$nextTick(()=>{
    //     this.footerShow = true
    //    })
    // },1000)
  },
  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style lang="less" scoped>
.app {
  /* width: 90%;
    border: 1px solid red; */
  display: flex;
  align-items: center;
  min-height: calc(100vh - 84px);
  position: relative;
  flex-direction: column;
  //   margin-bottom: 100px;

  .box-card {
    // width: 95%;
    background: white;
    margin-top: 30px;

    .formItem {
      display: flex;
    }
    .collapse-button {
      width: 100%;
      display: flex;
      justify-content: center;
      margin-top: 30px;
    }
  }
  .footer {
    width: 100%;
    height: 60px;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 100px;
    background-color: rgb(255, 255, 255);
  }
}
</style>